var express = require('express')
var mysql      = require('mysql');
var cfg = require('../config')
var connection=cfg.connection;

var app=express();
var request = require('request');
const utils = require('../react/utils');

var log4js = require('log4js');
var logger =  log4js.getLogger('fileLog'); // 此处的日志，会在 console 和文件中都输出
const fs = require("fs");
const path = require('path');
const schedule = require("node-schedule");

//定时器任务
var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(1, 6)];
rule.hour = cfg.schedule.hour;
rule.minute = cfg.schedule.minute;

var j = schedule.scheduleJob(rule, function(){

   logger.info("每天"+cfg.schedule.hour+":"+cfg.schedule.minute+"数据更新");

    var _url=cfg.productApi.url+cfg.productApi.entityName.SSDs+"()?api_key="+cfg.productApi.api_key
    _url+="&$expand=Family,Series&$filter=Family/FamilyId eq 83426 or Family/FamilyId eq 83424 or Family/FamilyId eq 83425 or Family/FamilyId eq 94489&$format=json&$orderby=ProductName desc"

    request(_url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            logger.info("访问成功")

            fs.writeFile(path.join('./', 'productData.json'), body, function (err) {
                if (err) throw err;
                logger.info("数据写入成功");
            });
        }
        else{
            logger.info(_url)
            logger.info("后台通信端错误。");
        }

    });


});








var item=[]
var products=[]
exports.product_cate=(req,res)=>{
    item.length=0;products.length=0//清空
    var rf=require("fs");
    rf.readFile("./productData.json",'utf-8',function(err,data){
        if(err){
            console.log(err)
            logger.info("error");
        }else{
            var obj= eval("("+data+")");//string 转换成object类型

            var arry=obj.d;
            const tempFamily=[]

            var tempSeries=[]
            arry.forEach((x,index)=>{
                const productItem=[]
                if(tempSeries.indexOf(x.ProductSeriesId)<=-1){
                    //在数组中还不存在该familyid
                    tempSeries.push(x.ProductSeriesId)
                    productItem.push(x)
                    products.push({"productSeriesId":x.ProductSeriesId, "productItem":productItem})

                }else {
                    var i=tempSeries.indexOf(x.ProductSeriesId)//数组中同数据的index

                    products[i].productItem.push(x)
                }
            })


            arry.forEach((x,index)=>{
                const seriesItem=[]
                let _count=0
                if(tempFamily.indexOf(x.ProductFamilyId)<=-1){
                    //在数组中还不存在该familyid
                    tempFamily.push(x.ProductFamilyId)
                    products.forEach(product=>{
                        if(product.productSeriesId==x.ProductSeriesId){
                            _count=product.productItem.length

                        }
                    })

                    seriesItem.push({data:x.Series,count:_count})
                    item.push({"familyid":x.ProductFamilyId, "series":seriesItem})

                }else{

                    var i=tempFamily.indexOf(x.ProductFamilyId)//数组中同数据的index


                    var isExist=false;
                    item[i].series.forEach(y=>{
                        if(y.data.SeriesId!= x.ProductSeriesId) {
                            isExist = true
                        }else{
                            isExist=false
                        }
                    })
                    if(isExist){
                        products.forEach(product=>{
                            if(product.productSeriesId== x.ProductSeriesId){

                                _count=product.productItem.length
                            }
                        })
                        item[i].series.push({data:x.Series,count:_count})
                    }

                }
            })



        }
    });


    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var  sql='SELECT * from category ';

    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempAccount.push(x)
        })

        res.render('product_cate', { layout: 'layout.ejs',title: 'SSD微信公众号-产品信息',result:tempAccount })
    });
    connection.end();
    logger.info("-------------------web product_cate-------------------")
}

exports.product_series=(req,res)=>{
    const  familyId=req.query.familyId

    //console.log(item)
    let seriesItem=[]
    item.forEach(x=>{
        if(x.familyid==familyId){

            seriesItem.push(x.series)

        }
    })



    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempCate =[];
    var sqlCate='SELECT * from category ';
    connection.query(sqlCate, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempCate.push(x)
        })
        res.render('product_series', { layout: 'layout.ejs',title: 'SSD微信公众号-产品信息',result:seriesItem,currentFamilyId:familyId,cate:tempCate })
    });
    connection.end();



}

exports.product=(req,res)=>{

    const  productSeriesId=req.query.productSeriesId;
    let productItem=[]
    products.forEach(product=>{
        if(product.productSeriesId==productSeriesId){
            productItem=product.productItem
        }
    })
    const familyId=req.query.familyId;

    const para={
        currentFamilyId:familyId,
        currentSeriesId:productSeriesId
    }
    let seriesItem=[]
    item.forEach(x=>{
        if(x.familyid==familyId){

            seriesItem.push(x.series)

        }
    })


    res.render('product', { layout: 'layout.ejs',title: 'SSD微信公众号-产品信息',result:productItem,para:para,series:seriesItem})




}
function format(date){

    var year=date.getFullYear();
    var month=date.getMonth()+1<10 ? '0'+(date.getMonth()+1):(date.getMonth()+1);
    var day=date.getDate();
    var hours=date.getHours();
    var minutes=date.getMinutes()<10 ? '0'+date.getMinutes() : date.getMinutes();
    var seconds=date.getSeconds()<10 ? '0'+date.getSeconds() :date.getSeconds();
    var time=year+'/'+month+'/'+day+" "+hours+":"+minutes+":"+seconds;

    return time
}
exports.product_detail=(req,res)=>{
    const  productId=req.query.productId;
    console.log(productId)
    const para={
        currentCateId:"",
        currentSeriesId:""
    }
    let _result=""
    products.forEach(product=>{
        product.productItem.forEach(item=>{
            if(item.ProductId==productId){

                _result=item
            }
        })

    })
    let _time=""
    if( _result.LaunchDate!=null){
        var value = _result.LaunchDate.replace(/[^0-9]/ig,"");
        var date = new Date(parseInt(value))
        _time=format(date)
    }

    res.render('product_detail', { layout: 'layout.ejs',title: 'SSD微信公众号-产品信息',para:para,result:_result,time:_time})

}

exports.solution=(req,res)=>{

    const tempIndustry=[]
    const tempSolution=[]
    connection = mysql.createConnection(connection.config);
    connection.connect();
    var sqlIndustry='select * from sol_industry ';
    connection.query(sqlIndustry,(err,rows)=>{
        if(err) return false
        rows.map(x=>{
            tempIndustry.push(x)
        })

    })

    var sqlSolution="select * from solution order by Name desc"
    connection.query(sqlSolution,(err,rows)=>{
        if(err) return false
        rows.map(x=>{
            tempSolution.push(x)
        })
        res.render('solution',{title:'test',industryItem:tempIndustry,solutionItem:tempSolution})

    })
    connection.end()


}
exports.solution_detail=(req,res)=>{
    const  id=req.query.id;
    logger.info(id)
    connection = mysql.createConnection(connection.config);
    connection.connect();


    var sql="select * from solution where Id=\'"+id+"\'"
    logger.info("获取解决方案的id:",id)
    connection.query(sql,(err,rows)=>{
        if(err) return false
        const time=rows[0].Time
        res.render('solution_detail',{result:rows[0],time:utils.timeStampToDate(time)})

    })
    connection.end()

}

exports.whitePaper=(req,res)=>{
    logger.info("访问白皮书 页面")
    const temp=[]
    connection = mysql.createConnection(connection.config);
    connection.connect();
    var sql='select * from whitepage order by id desc ';
    connection.query(sql,(err,rows)=>{
        logger.info("rows",rows)
        rows.map(x=>{
            temp.push(x)
        })
        res.render("whitePaper",{result:temp})
    })
    connection.end()
}
exports.pageOnline=(req,res)=>{
    res.render("pageOnline",{pdfUrl:"./../public/front/pdfjs/test.pdf"})
}
exports.data_picCate=(req,res)=>{
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var sqlCate='SELECT * from category ';
    connection.query(sqlCate, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempAccount.push(x)
        })

        res.render("data_picCate",{result:tempAccount})
    });
    connection.end()
}
exports.data_poster=(req,res)=>{
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var sql='SELECT * from material_poster ';
    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempAccount.push(x)
        })

        res.render("data_poster",{result:tempAccount})
    });
    connection.end()
}
exports.data_poster_det=(req,res)=>{
    const  id=req.query.id;
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var sql='SELECT * from material_poster where Id=\' '+id+'\'';
    connection.query(sql, function(err, rows){
        if (err) return false;


        res.render("data_poster_det",{result:rows[0]})
    });
    connection.end()
}

exports.data_page=(req,res)=>{
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var sql='SELECT * from material_page ';
    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempAccount.push(x)
        })

        res.render("data_page",{result:tempAccount})
    });
    connection.end()
}
exports.data_page_det=(req,res)=>{
    const  id=req.query.id;
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempAccount =[];
    var sql='SELECT * from material_page where Id=\' '+id+'\'';
    connection.query(sql, function(err, rows){
        if (err) return false;


        res.render("data_page_det",{result:rows[0]})
    });
    connection.end()
}

exports.pics=(req,res)=>{
    const categoryId=req.query.categoryId;
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const tempSeries=[]

    var  sqlSeries='SELECT * from series  where CategoryId=\' '+categoryId+'\' order by Name desc';
    connection.query(sqlSeries, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            tempSeries.push(x)
        })

    });
    const  _picItems=[];
    var  sqlPics='SELECT * from material_pic  where CategoryId=\' '+categoryId+'\'';
    connection.query(sqlPics, function(err, rows){
        if (err) return false;


        tempSeries.forEach((series,index)=>{
            _picItems[index]=Object.assign({seriesName:series.Name,pic:series.Pic})
            rows.map(pic=>{
                if(series.Id==pic.SeriesId){
                    _picItems[index]=Object.assign({seriesName:series.Name,pic:series.Pic},pic)
                }
            })
        })

        res.render("pics",{seriesItems:tempSeries,picItems:_picItems})
    });
    connection.end()
}


exports.activity=(req,res)=>{
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const temp=[]
    var  sql='SELECT * from activity order by Year desc,Date desc';
    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            temp.push(x)
        })
        logger.info("查询到的活动",temp)
        res.render("activity",{items:temp})
    });
    connection.end()
}
exports.activity_detail=(req,res)=>{
    const id=req.query.id;
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const temp=[]
    var  sql='SELECT * from activity where Id=\''+id+'\'';
    connection.query(sql, function(err, rows){
        if (err) return false;
        logger.info("活动详情查询成功")
        res.render('activity_detail',{result:rows[0]})
    });
    connection.end()
}

exports.faq=(req,res)=>{
    logger.info("请求数据",req.query)
    const offset = parseInt(req.query.offset, 10) || 1;
    const num=parseInt(req.query.num, 10) || 10
    var limit = offset + ','+num;
    connection = mysql.createConnection(connection.config);
    connection.connect();
    const temp=[]
    var  sql='SELECT * from material_poster limit '+limit;
    logger.info(sql)
    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            //console.log(x.Id,x.Name)
        })

        logger.info(req.query.offset)
        if(req.query.offset==undefined){
            logger.info("执行了")

            res.render("faq",{result:rows})
        }else{
            res.json({result:rows})
        }




    });
    connection.end()

}


exports.video=(req,res)=>{
    const cate=req.query.cate;

    connection = mysql.createConnection(connection.config);
    connection.connect();
    const temp=[]
    var  sql='SELECT * from video  where Cate=\''+cate+'\' order by Id desc';
    connection.query(sql, function(err, rows){
        if (err) return false;
        rows.map(x=>{
            temp.push(x)
    })
    logger.info("查询到的视频",temp)
    res.render("video",{items:temp})
});
connection.end()

}